/**
 * 模板 和 用法说明 使劲往下翻 ，别翻过了最下面是垃圾代码
 */


var MyCart = Class.create();

MyCart.prototype = {
    goods: [],//购物车数据
    listData: [],//商品列表原始数据
    listId: "",//商品列表外围容器ID
    num: 0,
    total: 0,
    shop: 0,
    initialize: function (sid, listData) { // 构造函数
        if (sid != undefined) {
            this.setShop(sid)
            //获取本地数据
            this.setDataFromLocal()
        }
    },
    setShop: function (sid) {
        this.shop = sid;
    },
    setDataFromLocal: function () {
        var localCart = this.getLocalCart(this.shop)
        if (localCart != false) {
            localCart.goods.map(function (data,index) {
                log(data.checked = false)
                log(index)
                localCart.goods[index].checked = false;
                return data;

            });


            this.goods = localCart.goods
            this.listData = localCart.goods
            this.num = localCart.num
            this.total = localCart.total
        }
    },
    setListData: function (listData) {
        this.listData = listData
        //log(this)
        var _this = this
        _this.listData.map(function (data, index) {
            _this.listData[index].num = 0
            _this.goods.map(function (item) {
                if (item.id == data.id) {
                    _this.listData[index].num = item.num
                    _this.upDateItemInList(item.id,item.num)
                }
            })
        })
        return _this.listData;
    },
    set: function (id, goodsNum) {
        if (goodsNum < 0){
            return false;
        }
        var num = 0
        var total = 0
        var findIndex = -1;
        // log(id)
        // log(goodsNum)
        // log(this.goods)
        // return;
        this.goods.map(function (data, index) {
            if (data.id == id) {
                findIndex = index
                data.num = goodsNum;
                //data.checked = true;
            }
            if (data.checked) {
                //统计总数
                num += data.num
                //统计总金额
                total += data.num * data.price
            }
        })
        // log(this.goods)
        if (findIndex != -1 && goodsNum == 0) {
            this.goods = arrayDelIndex(this.goods, findIndex)
        }
        if (findIndex == -1 && goodsNum != 0) {
            var prod = this.getProdById(id)
            log(prod);
            // return;
            prod.num = goodsNum
            this.goods.push(prod)
            //统计总数
            num += prod.num
            //统计总金额
            total += prod.num * prod.price
        }
        this.num = num
        this.total = total
        this.setLocalCart()
        this.setView()
    },
    getProdById: function (id) {
        //log(id)
        var findData = {};
        this.listData.map(function (data) {
        // this.goods.map(function (data) {
            //log(data)
            if (data.id == id) {
                findData = data
            }
        })
        if(findData == {}) {
            // this.listData.map(function (data) {
            this.goods.map(function (data) {
                //log(data)
                if (data.id == id) {
                    findData = data
                }
            })
        }
        return findData
    },

    //总购物车本地本地化存储

    getLocalCarts: function () {
        var carts = getLocData("carts");
        var data = {};
        try {
            data = JSON.parse(carts)
        } catch (e) {
            //取出的数据不是个json对象，这里人认为是错误的
            return false;
        } finally {
            //不做任何处理
        }
        if (JSON.stringify(data) == "[]") {
            data = {}
        }
        return data;
    },

    clearAll: function () {
        //appcan.locStorage.val("carts",{})
    },
    clearThis: function () {
        this.goods = []
        this.num = 0
        this.total = 0
        this.setLocalCart()
    },
    getLocalCart: function () {
        var carts = this.getLocalCarts();
        if (!carts) {
            //没有数据
            return false;
        } else {
            if (carts["shop_" + this.shop] != undefined) {
                return carts["shop_" + this.shop];
            } else {
                return false;
            }
        }
    },

    setLocalCart: function () {
        var _this = this
        var sid = this.shop
        //获取本地购物车总数据
        var carts = this.getLocalCarts();
        if (!carts) {
            carts = {}
        }
        //获取当前店铺购物车数
        carts["shop_" + sid] = {
            goods: _this.goods,
            num: _this.num,
            total: _this.total
        };
        setLocData("carts", carts)
    },

    createView: function () {
        var html = $('' +
            '<div class="MyCartSumBox w100 flex-r flex-center flex-fill" style="position: fixed;bottom: 0;">' +

            '<div class="flex4 bc1 pad10 flex-r flex-end flex-fill fs8 c13">' +
            '<div class="c3 flex-center"> <span class="fa fa-shopping-cart"></span> </div>' +
            '<div class="MyCartSumNum marl5 flex-center">0</div>' +
            '<div class="fs8 tam pad5">件商品，共计￥</div>' +
            '<div class="MyCartSumTotal flex-center c3 flex1">0</div>' +
            '<div class="MyCartClear flex-center c3"><span class="btn-small fs8 bc3 c11 round10">清空</span></div>' +
            '</div>' +

            '<div class="MyCartPay flex1 bc2 pad5 flex-center cf">下单</div>' +

            '</div>')
        $("body").append(html)

        //创建工具栏按钮监听事件
        var _this = this
        ontap(".MyCartClear", function () {//清空购物车
            $(".MyCartNum").html("0")
            _this.goods = [];
            _this.num = 0;
            _this.total = 0;
            _this.setLocalCart();
            _this.setView();
        })
        this.setView();
    },

    removeView: function () {
        $(".MyCartSumBox").remove()
    },

    setView: function () {
        $(".MyCartSumNum").text(this.num)
        $(".MyCartSumTotal").text(this.total.toFixed(2))
        // $(".MyCartSumTotal").text(this.total)
        if (this.num == 0) {
            $(".MyCartSumBox").hide()
        } else {
            $(".MyCartSumBox").show()
        }
    },
    setOnPayEvent: function (func) {
        var _this = this
        ontap(".MyCartPay", function () {
            func(_this)
        })
    },
    setOnSetEvent: function (funcAdd, funcRed) {
        //创建商品列表按钮监听事件
        var _this = this
        //$(".MyCartAdd")
        $(".MyCartAdd").off("click").on("click", function () {
            var _thisEle = $(this)
            var id = _thisEle.data("id")
            var numBox = _thisEle.parent().find(".MyCartNum");
            var numCur = numBox.text() * 1
            numBox.text(numCur + 1)
            if (_thisEle.hasClass("c12")) {
                _thisEle.removeClass("c12").addClass("c3")
                _thisEle.parent().find(".MyCartRed").removeClass("c12").addClass("c3")
            }
            _this.set(id, numCur + 1)
            if (funcAdd != undefined) {
                funcAdd()
            }
        }).each(function () {//新进入页面时按钮颜色要更新一下
            var _thisEle = $(this)
            if (_thisEle.parent().find(".MyCartNum").text() != "0") {
                _thisEle.removeClass("c12").addClass("c3")
                _thisEle.parent().find(".MyCartRed").removeClass("c12").addClass("c3")
            }
        })
        $(".MyCartRed").off("click").on("click", function () {
            var _thisEle = $(this)
            var id = _thisEle.data("id")
            var numBox = _thisEle.parent().find(".MyCartNum");
            var numCur = numBox.text() * 1
            var numTar = numCur - 1;
            if (numTar < 0) {
                return;
            }

            numBox.text(numCur - 1)
            if (numCur - 1 == 0) {
                _thisEle.removeClass("c3").addClass("c12")
                _thisEle.parent().find(".MyCartAdd").removeClass("c3").addClass("c12")
            }
            _this.set(id, numCur - 1)
            if (funcRed != undefined) {
                funcRed()
            }
        })
    },
    upDateItemInList: function (id,num) {
        var _thisEle = $("#MyCartNum" + id)
        _thisEle.find(".MyCartNum").text(num)
        if (num > 0) {

            _thisEle.parent().find(".MyCartAdd").removeClass("c12").addClass("c3")
            _thisEle.parent().find(".MyCartRed").removeClass("c12").addClass("c3")
        }
    }

};



//加减按钮模板
//<div class="ListBtn flex-r flex-end">
//<div class="MyCartRed c12 flex1 padl10 padr10 flex-center round30"
//data-ontap="red" data-id="0" data-bind="attr:{'data-id':id}">
//<span class="fa fa-minus-circle fa-2x"></span>
//</div>
//<div class="num pad5 flex-center fs16" id=""  data-bind="attr:{'id':id}" >
//<span class="MyCartNum" data-bind="text:num">0</span>
//</div>
//<div class="MyCartAdd c12 flex1 padl10 padr10 flex-center round30"
//data-ontap="add" data-id="0" data-bind="attr:{'data-id':id}">
//<span class="fa fa-plus-circle fa-2x"></span>
//</div>
//</div>




//JS 页面代码
//
//var windowName = "shopIndex";
//var dataPage;
//var id = 0;
//var cart;
//appcan.ready(function(){
//    viewData = new MVVM.Model({});
//    onPullDownRefresh(function(){
//        getData()
//        log("onPullDownRefresh");
//    });
//    onWindowShow(function(){
//        log("onWindowShow");
//        //getData()
//    });
//    disablePullDownRefresh();
//    dataPage = getData4Page(windowName);
//    if (dataPage.id != undefined) {
//        id = dataPage.id
//    }
//    log(dataPage)
//    cart = new MyCart(id)
//    cart.setOnSetEvent();
//    cart.setOnPayEvent(function (data) {
//        goto("cart",{id:data.shop})
//    })
//    cart.createView();
//    getData()
//
//});
//function getData() {
//    apiGet("/app/user/shop/index",{id:id}, function (res) {
//        log(res.d)
//        var shop = res.d.shop
//        var goods = res.d.goods
//        goods = cart.setListData(goods);
//        viewData["shop"] = shop;
//        svd("shop");
//        viewData["goods"] = {goods:goods};
//        svd("goods");
//        cart.setOnSetEvent();
//    })
//}





















//垃圾代码

//add: function (id) {
//    var num = 0
//    var total = 0
//
//    var find = 0;
//    this.goods.map(function (data) {
//        if (data.id == id) {
//            find = 1
//            if (data.num == undefined) {
//                data.num = 1;
//            }else {
//                data.num++
//            }
//        }
//        //统计总数
//        num += data.num
//        //统计总金额
//        total += data.num*data.price
//    })
//    logJson(find)
//    logJson(this.goods)
//    if (find == 0) {
//        var prod = this.getProdById(id)
//        prod.num = 1
//        this.goods.push(prod)
//        logJson(this.goods)
//
//        //统计总数
//        num += prod.num
//        //统计总金额
//        total += prod.num * prod.price
//    }
//
//    this.num = num
//    this.total = total
//    logJson(this.goods)
//    this.setLocalCart()
//    this.setView()
//},
//red: function (id) {
//
//    //var prod = this.getProdById(id)
//    var num = 0
//    var total = 0
//    var findIndex = -1;
//    this.goods.map(function (data , index) {
//        if (data.id == id) {
//            findIndex = index
//            if (data.num == 0) {
//                data.num = 0;
//            }else {
//                data.num--
//            }
//        }
//        //统计总数
//        num += data.num
//        //统计总金额
//        total += data.num*data.price
//    })
//    if (findIndex != -1) {
//        this.goods = arrayDelIndex(this.goods , findIndex)
//    }
//
//    this.num = num
//    this.total = total
//    logJson(this.goods)
//    this.setLocalCart()
//    this.setView()
//}

